package y2017.m10.d12;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpServer {
    public static void main(String[] args) throws Exception {
        //创建接收端的socket对象
        DatagramSocket ds = new DatagramSocket(9999);

        //接受来自客户端的数据
        while (true) {
            //创建数据包
            byte[] buf = new byte[1024];
            int length = buf.length;
            DatagramPacket dp = new DatagramPacket(buf, length);

            //接受来自客户端的数据
            ds.receive(dp);

            //解析数据包中的数据
            byte[] data = dp.getData();
            int len = dp.getLength();
            String s = new String(data, 0, len);
            if ("q".equalsIgnoreCase(s)) {
                System.out.println("server break......");
                break;
            }
            System.out.println("clint send : " + s);
            InetAddress address = dp.getAddress();
            String hostName = address.getHostName();
            System.out.println("hostName is " + hostName);
            String hello = "Hello World";
            dp.setLength(hello.length());
            dp.setData(hello.getBytes());
            ds.send(dp);
        }
    }
}